/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.FeeZzsl;
import com.jeeplus.modules.fee.entity.ImportNewRe;
import com.jeeplus.modules.fee.service.FeeZzslService;
import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.entity.NewCustomers;
import com.jeeplus.modules.infor.entity.PriceCustomers;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.NewCustomersService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.NewBill;
import com.jeeplus.modules.tms.entity.NewPlanning;
import com.jeeplus.modules.tms.service.NewPlanningService;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.fee.entity.NewRe;
import com.jeeplus.modules.fee.service.NewReService;


/**
 * 应收Controller
 * @author 李超辉
 * @version 2019-05-22
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/newRe")
public class NewReController extends BaseController {

	@Autowired
	private NewReService newReService;
	@Autowired
	private SlService slService;
	@Autowired
	private NewCustomersService newCustomersService;
	@Autowired
	private NewPlanningService newPlanningService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private FeeZzslService zzslService;
	@ModelAttribute
	public NewRe get(@RequestParam(required=false) String id) {
		NewRe entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = newReService.get(id);
		}
		if (entity == null){
			entity = new NewRe();
		}
		return entity;
	}
	
	/**
	 * 应收列表页面
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/newReList";
	}
	/**
	 * 开票页面
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/fee/1/newReList";
	}
	/**
	 * 应收报表
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/fee/2/newReList";
	}

	/**
	 * 应收报表
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/fee/3/newReList";
	}

	/**
	 * 应收报表
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/fee/4/newReList";
	}

	/**
	 * 应收报表
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list5"})
	public String list5() {
		return "modules/fee/5/newReList";
	}


	/**
	 * 应收报表
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list6"})
	public String list6() {
		return "modules/fee/6/newReList";
	}


	/**
	 * 应收报表
	 */
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = {"list7"})
	public String list7() {
		return "modules/fee/7/newReList";
	}
	
		/**
	 * 应收列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		Page<NewRe> page = newReService.findPage(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}
	/**
	 * 开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		newRe.setStatus("2");
			Page<NewRe> page = newReService.findPage(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}

	/**
	 * 开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		newRe.setStatus("2");
		Page<NewRe> page = newReService.findPage(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}
	/**
	 * 开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data4")
	public Map<String, Object> data4(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		newRe.setStatus("2");
		Page<NewRe> page = newReService.findPage1(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}
	/**
	 * 开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data5")
	public Map<String, Object> data5(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		newRe.setStatus("2");
		Page<NewRe> page = newReService.findPage2(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}
	/**
	 * 开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data6")
	public Map<String, Object> data6(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		newRe.setStatus("2");
		Page<NewRe> page = newReService.findPage3(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}
	/**
	 * 开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:list")
	@RequestMapping(value = "data7")
	public Map<String, Object> data7(NewRe newRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newRe.setProject(pro);
		}
		newRe.setStatus("2");
		Page<NewRe> page = newReService.findPage4(new Page<NewRe>(request, response), newRe);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑应收表单页面
	 */
	@RequiresPermissions(value={"fee:newRe:view","fee:newRe:add","fee:newRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(NewRe newRe, Model model) {
		model.addAttribute("newRe", newRe);
		return "modules/fee/newReForm";
	}

	/**
	 * 保存应收
	 */
	@ResponseBody
	@RequiresPermissions(value={"fee:newRe:add","fee:newRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(NewRe newRe, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, newRe)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		newReService.save(newRe);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存应收成功");
		return j;
	}

	/**
	 * 刷新计费
	 */
	@ResponseBody
	@Transactional(readOnly = false)
	@RequestMapping(value = "sxjf")
	public AjaxJson jf(String ids, RedirectAttributes redirectAttributes)throws Exception {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		boolean bol=true;
		for(String id : idArray) {
			NewRe p = newReService.get(id);
			NumberFormat nf = NumberFormat.getInstance();
			//创建应收
			NewPlanning p1=newPlanningService.get(p.getPid());
			NewCustomers n = newCustomersService.get(p1.getCustomer());
			List<PriceCustomers> li = n.getPriceCustomersList();
			boolean bo = false;
			PriceCustomers pc = null;
			for (PriceCustomers pp : li) {
				if (pp.getWidth().equals(p1.getWidth()) && pp.getZylx().equals(p1.getZylx())) {
					pc = pp;
					bo = true;
				}
			}
			if (!bo) {
				j.setMsg("请先维护运价");
				j.setSuccess(false);
				return j;
			}
			String dj = pc.getJsjg();
			String fj = pc.getFjf();
			double pri = Double.parseDouble(dj);
			double ppp = Double.parseDouble(fj);
			Goods g = goodsService.get(p1.getName().getId());
			Double wei = Double.parseDouble(p.getWeight().replaceAll(",", ""));
			Double vo = Double.parseDouble(p1.getVoulm().replaceAll(",", ""));
			String o = g.getMoney();
			if (o == "" || o == null) {
				o = "0";
			}
			Double xs = Double.parseDouble(o);
			double pr = pri * wei * xs;
			p.setPrice(pri + "");
			p.setSurplus(nf.format(pr).replaceAll(",", ""));
			FeeZzsl f = new FeeZzsl();
			f.setPro(p1.getPro());
			String sll = zzslService.findList(f).get(0).getSl();
			p.setSl(sll);
			Double hs = pr * (1 + Double.parseDouble(sll));
			p.setHs(nf.format(hs).replaceAll(",", ""));
			p.setFreight(nf.format(hs).replaceAll(",", ""));



//			NewBill nb=new NewBill();
//			nb.setPlanning(p.getId());
//			nb.setPro(p.getPro());
//			List<NewBill> bills=newBillService.findList(nb);
//			double zyf=0.0;
//			double htfy=0.0;
//			double zcfy=0.0;
//			for(NewBill bill:bills){
//				zyf+=Double.parseDouble(bill.getZyf());
//				htfy+=Double.parseDouble(bill.getHtfy());
//				zcfy+=Double.parseDouble(bill.getZcfy());
//			}
//			r.setZyf(nf.format(zyf).replaceAll(",",""));
//			r.setHtfy(nf.format(htfy).replaceAll(",",""));
//			r.setZcfy(nf.format(zcfy).replaceAll(",",""));


			newReService.save(p);

		}
		j.setMsg("计费成功");
		return j;


	}
	/**
	 * 确认
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(NewRe n, RedirectAttributes redirectAttributes) {
		n.setStatus("2");
		NumberFormat nf = NumberFormat.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
//		Sl sl=slService.findUniqueByProperty("pro", n.getProject());
		String sr=n.getFreight();
		String zc=n.getZyf();
		String xs=n.getXsyf();
		String xx=n.getXxyfyk();
		String kp=n.getKpyf();
		double mlr=Double.parseDouble(sr)-Double.parseDouble(zc);
		double a=Double.parseDouble(sr)*0.1;
		double b=Double.parseDouble(xs)*73/1000;
		double c=Double.parseDouble(xx)*0.13;
		double d=Double.parseDouble(kp)*0.09;
		double sj=a-b-c-d;
		double lrl=(mlr-sj)/Double.parseDouble(sr);
        n.setMlr(nf.format(mlr).replaceAll(",",""));
		n.setSj(nf.format(sj).replaceAll(",",""));
		n.setLrl(df.format(lrl));
		AjaxJson j = new AjaxJson();
		newReService.save(n);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 删除应收
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(NewRe newRe, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		newReService.delete(newRe);
		j.setMsg("删除应收成功");
		return j;
	}
	
	/**
	 * 批量删除应收
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			newReService.delete(newReService.get(id));
		}
		j.setMsg("删除应收成功");
		return j;
 	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:newRe:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(NewRe newRe, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<NewRe> page = newReService.findPage(new Page<NewRe>(request, response, -1), newRe);
    		new ExportExcel("应收", NewRe.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ImportNewRe> list = ei.getDataList(ImportNewRe.class);
			for (ImportNewRe newRe : list){
				try{
					NewRe nn=newReService.get(newRe.getId());
					nn.setQr(newRe.getQr());
					newReService.save(nn);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/newRe/list1";
    }
	
	/**
	 * 下载导入应收数据模板
	 */
	@RequiresPermissions("fee:newRe:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收数据导入模板.xlsx";
    		List<NewRe> list = Lists.newArrayList();
    		new ExportExcel("应收数据", NewRe.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/newRe/?repage";
    }

}